<?php


namespace App\Traits\Controllers;

use Illuminate\Http\Request;

trait IndexTraits
{
    /**
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     */

    public function index(Request $request)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);

        $data = $this
            ->getQuery()
            ->pimp()//自动转换where条件
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->transformer));
    }

    /**
     * 处理搜索数据
     *
     * @param Request $request
     * @return Request
     */
    public function formatIndexQuery(Request $request)
    {

        $searchableModels = $this->getQuery()->searchableModels ?? [];

        if (empty($searchableModels)) return $request;

        foreach ($request->all() as $key => $value) {
            //data_get 函数使用「.」符号从多维数组或对象中根据指定键检索值,default支持默认值，没有返回默认值
            $field_model = data_get($searchableModels, $key, '');

            if (!empty($field_model)) {
                //str_replace() 函数替换字符串中的一些字符（区分大小写）。
                $val = str_replace('field', $value, $field_model);
                //添加到$request数组中
                $request->offsetSet($key, $val);
            }
        }

        return $request;
    }

    /**
     * 获取一页的数量
     *
     * @return mixed
     */
    public function getPageLimit()
    {
        $limit = request()->input('pageSize');

        if ($limit < 0 || empty($limit)) {
            $limit = config('paginate.limit');
        } elseif ($limit > 100) {
            $limit = 100;
        }

        return $limit;
    }


}
